#include "music_window.h"
#include "ui_music_window.h"
#include "main_window.h"
#include <QPixmap>
#include <QPen>
#include <QMediaPlayer>
#include <QListWidgetItem>
extern Main_Window *pmain_window;

Music_window::Music_window(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Music_window)
{
    ui->setupUi(this);

      //设置声音初始值
    ui->voice_lound->setValue(50);
    // 安装事件过滤器,使得label能够实现按键检测
    ui->Back_menu->installEventFilter(this);
    ui->start->installEventFilter(this);
    ui->up->installEventFilter(this);
    ui->down->installEventFilter(this);
    ui->shunxu->installEventFilter(this);
    ui->list->installEventFilter(this);
    ui->voice->installEventFilter(this);

    //初始化歌曲列表和歌曲
    player = new QMediaPlayer;
    playerlist = new QMediaPlaylist(player);

    fileList = getFileNames(this->MusicPath);
    player->setVolume(50);
    for(int i=0;i<fileList.size();i++)
    {
       QString fileName=fileList.at(i);
       std::string str = fileName.toStdString();
       const char *name= str.c_str();
       int j=0;
       while(name[j]!='\0'){
           music_singl[i][j]=name[j];
           j++;
       }
       playerlist->addMedia(QUrl::fromLocalFile(MusicPath+"/"+fileName));
    }
   // qDebug()<<"music_name is:"<<music_name<<"music_author is:"<<music_singl;
    int i=0;
    do{

      //  qDebug()<<music_singl[i];
        i++;
    }while(music_singl[i][0]!='\0');
    playerlist->setCurrentIndex(0);
    player->setPlaylist(playerlist);
    /*设置圆盘转动*/
    connect(&timer,&QTimer::timeout,[this]
       {
           angle += 1.0;
           if(angle == 360)
               angle = 0.0;
           update();
       });
    connect(&shunxu_timer,&QTimer::timeout,[this]
       {
           ui->bof_txt->hide();
           shunxu_timer.stop();
       });
       timer.stop();
    connect(ui->music_list,SIGNAL(currentRowChanged(int)),this,SLOT(play_list_music(int)));
    connect(player, SIGNAL(metaDataChanged()), this, SLOT(musicInfo()));
    //进度条改变时播放位置随着改变
    connect(ui->progressBar,SIGNAL(sliderMoved(int)),this,SLOT(setPlayerPosition(int)));
    //当播放歌曲位置改变时progressBar设置对应的位置 对应的播放时间与总时间的显示
    connect(player,SIGNAL(positionChanged(qint64)),this,SLOT(positionChanged(qint64)));
    connect(player, SIGNAL(durationChanged(qint64)), this, SLOT(durationChanged(qint64)));

    //音量大小设置
    connect(ui->voice_lound, SIGNAL(valueChanged(int)), this, SLOT(volumChange(int)));

    //歌词显示
    connect(player,SIGNAL(positionChanged(qint64)),this,SLOT(updateSongLrc(qint64)));//随时间变化歌词


    connect(playerlist,&QMediaPlaylist::currentMediaChanged,this,&Music_window::updateSongLyclist);//歌曲变化就查找和提取歌词
    connect(player,&QMediaPlayer::stateChanged,this,&Music_window::updateSongLyclist);//第一首歌播放时候没有更新歌词，笨办法就是this->Music_show();
    Music_show();
}

Music_window::~Music_window()
{
    delete ui;
}
void Music_window::updateSongLrc(qint64 position)//随时间变化而变化显示歌词
{
    Lyric->showcontent(position);//更新歌词位置
}

void Music_window::volumChange(int position)
{
    Vposition=position;
    player->setVolume(position);
    if(position <= 6)
    {
        QPixmap *pax5 = new QPixmap(":/picture/music_window/音量.png");
        ui->voice->setPixmap(*pax5);
    }
    else
    {
        QPixmap *pax5 = new QPixmap(":/picture/music_window/音量.png");
        ui->voice->setPixmap(*pax5);
    }
    player->setVolume(position);
}
// 当progressBar改变时，构造歌曲总时间
void Music_window::durationChanged(qint64 duration)
{
    ui->progressBar->setRange(0,duration);// progressBar的范围从0到duration（总时间）
    totalTime=new QTime(0,(duration/60000)%60,(duration/1000)%60);
    ui->endTime->setText(totalTime->toString("mm:ss"));//歌曲总时间
}
// 当播放歌曲位置改变时，progressBar设置对应的位置、对应的播放时间与总时间的显示
void Music_window::positionChanged(qint64 position)//
{
    ui->progressBar->setValue(position);//position 单位：毫秒 1000ms=1s
    currentTime=new QTime(0,(position/60000)%60,(position/1000)%60);//构造当前时间（小时,分钟,秒和毫秒）
    QString t=currentTime->toString("mm:ss");
    ui->strTime->setText(currentTime->toString("mm:ss"));//播放时间   输出时间格式09:02（都是两位）

    QString mm = t.mid(0,2);
    QString ss = t.mid(3, 2);
    int m = mm.toInt();
    int s = ss.toInt();
    time = m*60*1000 + s*1000;
}

void Music_window::setPlayerPosition(int position)
{
    player->setPosition(position);

}
void Music_window::Music_show(){
    ui->bof_txt->hide();
    ui->music_list->hide();
    ui->voice_lound->hide();
    ui->music_list->setStyleSheet("background-color:transparent");
    Lyric->show();

    QPalette pe;
    pe.setColor(QPalette::WindowText,Qt::white);
    ui->strTime->setPalette(pe);
    ui->endTime->setPalette(pe);
    ui->author_label->setPalette(pe);
    ui->name_label->setPalette(pe);
    ui->bof_txt->setPalette(pe);
    QPixmap *pax1 = new QPixmap(":/picture/music_window/列表循环.png");
    ui->shunxu->setPixmap(*pax1);
    ui->shunxu->setScaledContents(true);
    QPixmap *pax2 = new QPixmap(":/picture/music_window/上一首.png");
    ui->up->setPixmap(*pax2);
    ui->up->setScaledContents(true);
    QPixmap *pax3 = new QPixmap(":/picture/music_window/开始.png");
    ui->start->setPixmap(*pax3);
    ui->start->setScaledContents(true);
   QPixmap *pax4 = new QPixmap(":/picture/music_window/下一首.png");
    ui->down->setPixmap(*pax4);
    ui->down->setScaledContents(true);
    QPixmap *pax5 = new QPixmap(":/picture/music_window/播放列表.png");
    ui->list->setPixmap(*pax5);
    ui->list->setScaledContents(true);


    QPixmap *pax = new QPixmap(":/picture/main_window/返回菜单.png");
    ui->Back_menu->setPixmap(*pax);
    ui->Back_menu->setScaledContents(true);

    QPixmap *pax_v = new QPixmap(":/picture/music_window/音量.png");
    ui->voice->setPixmap(*pax_v);
    ui->voice->setScaledContents(true);

    ui->name_label->setAlignment(Qt::AlignCenter);
    ui->author_label->setAlignment(Qt::AlignCenter);


    ui->name_label->setText(this->music_name);
    ui->author_label->setText(this->music_author);

    for(int i=0;music_singl[i][0]!='\0';i++){
        addItem(music_singl[i]);
    }
}
void Music_window::play_list_music(int index)
{
    QPixmap pax;
    playerlist->setCurrentIndex(index);
    ui->music_list->hide();
    timer.start();
    pax.load(":/picture/music_window/暂停.png");
    ui->start->setPixmap(pax);
    music_flag = 1;
    player->play();
    isPlay=true;
}
void Music_window::addItem(char *name)
{
    QListWidgetItem *item = new QListWidgetItem;
    item->setText(name);
    if (name != NULL) {
        ui->music_list->addItem(item);
    }
}
QStringList Music_window::getFileNames(const QString &path)
{
  QDir dir(path);
  QStringList nameFilters;
  nameFilters << "*.mp3";
  QStringList files = dir.entryList(nameFilters, QDir::Files|QDir::Readable, QDir::Name);
  return files;
}

bool Music_window::eventFilter(QObject *obj, QEvent *event)
{
    int MusicCurrent;
    int MusicCount;
    QPixmap *pax = new QPixmap(":/picture/music_window/开始.png");

    if (obj == ui->Back_menu)//指定某个QLabel
     {
         if (event->type() == QEvent::MouseButtonPress) //鼠标点击
         {
             QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event); // 事件转换

             if(mouseEvent->button() == Qt::LeftButton)
             {
                    this->hide();
                    pmain_window->show();
                 return true;
             }
             else
             {
                 return false;
             }
         }
         else
         {
             return false;
         }
     }
    else if (obj == ui->start)//指定某个QLabel
     {
         if (event->type() == QEvent::MouseButtonPress) //鼠标点击
         {
             QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event); // 事件转换

             if(mouseEvent->button() == Qt::LeftButton)
             {
                 if(music_flag == 0){
                     pax->load(":/picture/music_window/暂停.png");
                     ui->start->setPixmap(*pax);
                     music_flag = 1;
                     player->play();
                     isPlay=true;
                     timer.start();
                 }
                 else{
                     pax->load(":/picture/music_window/开始.png");
                     ui->start->setPixmap(*pax);
                     music_flag = 0;
                     player->pause();
                     isPlay=false;
                     timer.stop();
                 }

                 return true;
             }
             else
             {
                 return false;
             }
         }
         else
         {
             return false;
         }
     }
    else if (obj == ui->up)//指定某个QLabel
     {
         if (event->type() == QEvent::MouseButtonPress) //鼠标点击
         {
             QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event); // 事件转换

             if(mouseEvent->button() == Qt::LeftButton){
             //    picture_flag = rand()%4;
            //     qDebug()<<picture_flag;
                 //播放列表为空，按钮不可用，直接返回
                 if(!(playerlist->isEmpty())){
                   MusicCount=playerlist->mediaCount();
                   MusicCurrent=playerlist->currentIndex();
                   if(MusicCurrent==0){
                       playerlist->setCurrentIndex(MusicCount-1);
                   }
                   else playerlist->setCurrentIndex(MusicCurrent-1);
                 }
                 if(isPlay == 1) player->play();
                 else player->pause();
                 QString musicName=player->metaData("Title").toString().toUtf8().data();
                 QString authorName=player->metaData("Author").toString().toUtf8().data();
              //   qDebug()<<musicName<<authorName;
                 return true;
             }
             else{
                 return false;
             }
         }
         else
         {
             return false;

         }
     }
    else if (obj == ui->down)//指定某个QLabel
     {
         if (event->type() == QEvent::MouseButtonPress) //鼠标点击
         {
             QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event); // 事件转换

             if(mouseEvent->button() == Qt::LeftButton){
             //    picture_flag = rand()%4;
                 //播放列表为空，按钮不可用，直接返回
                 if(!(playerlist->isEmpty())){
                   MusicCount=playerlist->mediaCount();
                   MusicCurrent=playerlist->currentIndex();
                   if(MusicCurrent==MusicCount-1){
                       playerlist->setCurrentIndex(0);
                   }
                   else playerlist->setCurrentIndex(MusicCurrent+1);
                   if(isPlay == 1) player->play();
                   else player->pause();

                   return true;
                 }
                 else return  false;
             }
             else{
                 return false;
             }
         }
         else
         {
             return false;

         }
     }
    else if (obj == ui->shunxu){
        if (event->type() == QEvent::MouseButtonPress) //鼠标点击
        {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event); // 事件转换

            if(mouseEvent->button() == Qt::LeftButton){
                        if(shunxi_flag == 0){
                            QPixmap *pax1 = new QPixmap(":/picture/music_window/随机循环.png");
                            ui->shunxu->setPixmap(*pax1);
                            ui->shunxu->setScaledContents(true);

                            playerlist->setPlaybackMode(QMediaPlaylist::Random);//设置播放模式(顺序播放，单曲循环，随机播放等)
                            ui->bof_txt->setText("随机播放");
                            shunxi_flag = 1;
                        }
                        else if(shunxi_flag ==1){
                            QPixmap *pax1 = new QPixmap(":/picture/music_window/单曲循环.png");
                            ui->shunxu->setPixmap(*pax1);
                            ui->shunxu->setScaledContents(true);
                            playerlist->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);//设置播放模式(顺序播放，单曲循环，随机播放等)
                            shunxi_flag = 2;
                            ui->bof_txt->setText("单曲循环");
                        }
                        else if(shunxi_flag ==2){
                            QPixmap *pax1 = new QPixmap(":/picture/music_window/列表循环.png");
                            ui->shunxu->setPixmap(*pax1);
                            ui->shunxu->setScaledContents(true);
                            playerlist->setPlaybackMode(QMediaPlaylist::Loop);//设置播放模式(顺序播放，单曲循环，随机播放等)
                            shunxi_flag = 0;
                            ui->bof_txt->setText("顺序播放");
                        }
                        shunxu_timer.start(1500);
                        ui->bof_txt->show();
                         return true;
            }
            else return false;
        }
        else return false;
    }
    else if (obj == ui->list){
        if (event->type() == QEvent::MouseButtonPress) //鼠标点击
        {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event); // 事件转换

            if(mouseEvent->button() == Qt::LeftButton){
                        if(list_flag == 0){
                            ui->music_list->show();
                            Lyric->hide();
                            list_flag = 1;
                        }
                        else if(list_flag ==1){
                            ui->music_list->hide();
                            Lyric->show();
                            list_flag = 0;
                        }
                         return true;
            }
            else return false;
        }
        else return false;
    }
    else if (obj == ui->voice){
        if (event->type() == QEvent::MouseButtonPress) //鼠标点击
        {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event); // 事件转换

            if(mouseEvent->button() == Qt::LeftButton){
                        if(voice_flag == 0){
                            ui->voice_lound->show();
                            voice_flag = 1;
                        }
                        else if(voice_flag ==1){
                            ui->voice_lound->hide();
                            voice_flag = 0;
                        }

                         return true;
            }
            else return false;
        }
        else return false;
    }
     else
     {
         // pass the event on to the parent class
         return QWidget::eventFilter(obj, event);
     }
}
void Music_window::musicInfo(){
    int MusicCurrent=playerlist->currentIndex();
    int i=0;
    char mu_name[100]="\0";
    while(music_singl[MusicCurrent][i]!='_'){
        mu_name[i] = music_singl[MusicCurrent][i];
        i++;
    }
    int j=i+1;
    i=0;
    char mu_author[100]="\0";
    while(music_singl[MusicCurrent][j]!='.'){
        mu_author[i] = music_singl[MusicCurrent][j];
        j++;
        i++;
    }
    music_name = mu_name;
    music_author = mu_author;
    ui->name_label->setText(music_name);
    ui->author_label->setText(music_author);
    if(picture_show_flag == 0){
        picture_flag = rand()%4;
        picture_show_flag = 1;
    }
    else{
        picture_show_flag=0;
    }
    if(Lyric->isHidden())//如果隐藏的话就show，否则就hide
        {
            Lyric->show();
         }
}
void Music_window::updateSongLyclist()
{
    int index=playerlist->currentIndex();//获取当前位置
    QString songname_daihouzui=fileList.at(index);//提取在当前位置的文件名
    QStringList songnamelist = songname_daihouzui.split(".");//QString字符串分割函数
    QString songname=songnamelist[0];
    QString lycpath=MusicPath+"/" +songname+".lrc";
    Lyric->process(lycpath);
}
void Music_window::paintEvent(QPaintEvent *event){
    QPainter painter(this);
    QPen pen(QColor(255,255,255));
    QFont font;
    font.setFamily("Microsoft YaHei");
    QRect *rects = new QRect(100,90,250,250);
    painter.setPen(pen);

    /*背景颜色*/
    painter.setBrush(QColor(75,99,147));
    painter.drawRect(this->rect());

    painter.setRenderHint(QPainter::Antialiasing, true);
    QPoint centerPoint = rects->center();

    painter.save();
    painter.translate(centerPoint);
    int radius = (250 - 10 * 2 ) / 2;
    pen.setColor(Qt::red);
    pen.setWidth(5);
    painter.setPen(pen);
    painter.drawEllipse(QPoint(0, 0), radius/2, radius/2);

    QRect rect = QRect(-radius, -radius,
                       radius*2, radius*2);

    pen.setColor(Qt::blue);
    painter.setPen(pen);

    QRegion maskedRegion(rect, QRegion::Ellipse);
    painter.setClipRegion(maskedRegion);
    painter.rotate(angle);


    QString str = QString::number(picture_flag);
    picture_name.append(picture_local);
    picture_name.append(str);
    picture_name.append(".jpg");
    painter.drawPixmap(rect,QPixmap(picture_name));
    picture_name = "\0";
    painter.restore();
}

